import { defineComponent, computed, inject, reactive,watch } from "vue"
import deepcopy  from "deepcopy"

export default defineComponent({
	props: {
		modelValue: Object, // 确保类型匹配
		item: Object,
	},
	emits: ["update:modelValue","changeItem"],
	setup(props, ctx) {
		const config = inject("config")
		let state = reactive({
			editData:{}
		})
		const saveData = () =>{
			if(!props.item.value){
				props.modelValue.value = deepcopy(state.editData)
			}else{
				ctx.emit('changeItem',deepcopy(state.editData))
				// props.item.value = deepcopy(state.editData)
				// console.log(777,props.item.value,888,state.editData);
			}
		}
		const reset = ()=>{
			if(!props.item.value){
				state.editData = deepcopy(props.modelValue.value)
			}else{
				state.editData = deepcopy(props.item.value)
			}
		}
		watch(() => props.item.value, reset,{immediate:true})
		return () => {
			let tree = []
			if (!props.item.value) {
				tree.push(
					<>
						<ElFormItem label="容器宽度">
							<ElInput type="number" v-model={state.editData.container.width} placeholder="请输入容器宽度"></ElInput>
						</ElFormItem>
						<ElFormItem label="容器高度">
							<ElInput type="number" v-model={state.editData.container.height} placeholder="请输入容器宽度"></ElInput>
						</ElFormItem>
					</>
				)
			} else {
				tree.push(
					Object.entries(config.componentMap[props.item.value.key].props).map(([propName, propValue]) => {
						return (
							<ElFormItem label={propValue.label}>
								{{
									input: () => <ElInput v-model={state.editData.props[propName]}></ElInput>,
									color: () => <ElColorPicker v-model={state.editData.props[propName]}></ElColorPicker>,
									select: () => (
										<ElSelect v-model={state.editData.props[propName]}>
											{propValue.options.map((optionItem) => {
												return <ElOption label={optionItem.label} value={optionItem.value}></ElOption>
											})}
										</ElSelect>
									),
								}[propValue.type]()}
							</ElFormItem>
						)
					})
				)
			}
			return (
				<ElForm labelPosition="top" labelWidth="100%">
					{tree}
					<ElButton onClick={saveData} type="primary">保存</ElButton>
					<ElButton>取消</ElButton>
				</ElForm>
			)
		}
	},
})
